package com.vertx.starter;

import com.google.inject.Injector;
import com.vertx.starter.guice.GuiceFactory;
import io.vertx.core.Vertx;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class MainClass {

    public static void main(String[] args) {
        System.setProperty(
                "vertx.logger-delegate-factory-class-name",
                "io.vertx.core.logging.Log4j2LogDelegateFactory"
        );
        Vertx vertx = Vertx.vertx();
        registerShutdownHook(vertx);
        try {
            Injector injector = GuiceFactory.createInjector();
            Configure.getInstance().init(vertx);
            AppServiceLauncher appServiceLauncher = injector.getInstance(AppServiceLauncher.class);
            appServiceLauncher.launch(vertx).onSuccess(result -> {
                log.info("启动成功！");
            }).onFailure(e -> cleanup(vertx, e));
        } catch (Exception e) {
            cleanup(vertx, e);
        }
    }

    private static void registerShutdownHook(Vertx vertx) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            cleanup(vertx, (Throwable) null);
        }));
    }

    private static void cleanup(Vertx vertx, Throwable e) {
        log.info("开始清理工作!", e);
        vertx.close().onComplete((__) -> {
            log.error("结束清理工作!");
        });
    }
}
